package Thread;

import java.util.concurrent.CountDownLatch;

/**
 * @author: lqh
 * @description: 四个线程 A B C D，其中 D 要等到 A B C 全执行完毕后才执行，而且 A B C 是同步运行的
 *  （这个例子主要是 一个线程等待其他多个线程的问题，通过使用CountDownLatch 将需要等待的线程数设置进去，
 *  主线程调用await方法进入等待状态，其他线程执行完毕调用countDown方法将等待数减1，直到count为0，
 *  处于await状态的线程将继续执行。）
 * @program: Demo
 * @create: 2018-04-14 14:05
 **/
public class demo3 {
    public static void main(String[] args) {
        String[] theadArr = {"A","B","C","D"};
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //D
        new Thread(new Runnable() {
            @Override
            public void run() {
                String threadName = theadArr[3];
                System.out.println(threadName+" thread start...");
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(threadName+" thread finish...");
            }
        }).start();
        //A、B、C
        for (int i=0;i<3;i++){
            String threadName = theadArr[i];
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(threadName+" thread start...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(threadName+" thread finish...");
                    countDownLatch.countDown();
                }
            }).start();
        }
    }
}
